<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="试卷名称" prop="paperName">
        <el-input
          v-model="queryParams.paperName"
          placeholder="请输入试卷名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学科" prop="subjectId">
        <el-select
          clearable
          v-model="queryParams.subjectId"
          placeholder="请选择学科"
        >
          <el-option
            v-for="item in subjectList"
            :key="item.subjectId"
            :label="item.subjectName"
            :value="item.subjectId"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="开始时间" prop="limitStartTime">
        <el-date-picker
          clearable
          v-model="queryParams.limitStartTime"
          type="datetime"
          placeholder="请选择开始时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="limitEndTime">
        <el-date-picker
          clearable
          v-model="queryParams.limitEndTime"
          type="datetime"
          placeholder="请选择结束时间"
        >
          <!--   value-format="yyyy-MM-dd HH:mm:ss" -->
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb10">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['exam:paper:add']"
          >新增</el-button
        >
      </el-col>

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getPaperList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="paperList">
      <el-table-column label="试卷名称" align="center" prop="paperName">
        <template slot-scope="scope">
          <el-tooltip
            class="item"
            effect="dark"
            :content="scope.row.paperName"
            placement="right"
          >
            <span> {{ scope.row.paperName | ellipsis(0, 5) }}</span>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column label="试卷总分" align="center" prop="paperScore" />
      <el-table-column label="题目数量" align="center" prop="questionCount" />
      <el-table-column label="建议时长" align="center" prop="suggestTime" />
      <el-table-column
        sortable
        label="开始时间"
        align="center"
        prop="limitStartTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.limitStartTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        sortable
        label="结束时间"
        align="center"
        prop="limitEndTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.limitEndTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
        align="center"
        prop="status"
        v-if="checkPermi(['exam:paper:edit'])"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            @change="handleStatus(scope.row)"
            active-value="0"
            inactive-value="1"
          >
          </el-switch>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        width="180"
        class-name="small-padding fixed-width"
        v-if="
          checkPermi([
            'exam:paper:detail',
            'exam:paper:remove',
            'exam:paper:doexam',
          ])
        "
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-zoom-in"
            @click="handlePreview(scope.row)"
            v-hasPermi="['exam:paper:detail']"
            >查看</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDoExam(scope.row)"
            v-hasPermi="['exam:paper:doexam']"
            >考试</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['exam:paper:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getPaperList"
    />

    <!-- 查看试卷 -->
    <el-dialog
      :visible.sync="open"
      width="900px"
      append-to-body
      style="height: 1900px"
    >
      <el-card class="box-card">
        <div slot="header" class="clearfix paperInfo">
          <div>
            <el-tag>试卷名称：</el-tag>
            {{ paper.paperName }}
          </div>
          <div><el-tag>时间限制：</el-tag>{{ paper.suggestTime }} 分钟</div>
          <div>
            <el-tag>有效期</el-tag> {{ parseTime(paper.limitStartTime) }} 至
            {{ parseTime(paper.limitEndTime) }} 期间
          </div>
        </div>
        <show-question
          :score="paper.paperScore"
          :showRemoveQuestion="false"
          :showRemoveAll="false"
          :questions="questionList"
        ></show-question>
      </el-card>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPaper,
  getPaper,
  delPaper,
  updatePaperStatus,
} from "@/api/exam/paper";

import { doExam } from "@/api/exam/doExam";
import { listSubject } from "@/api/exam/subject";
import showQuestion from "@/components/exam/showQuestion";
import { checkPermi } from "@/utils/permission"; // 权限判断函数
export default {
  components: { showQuestion },
  name: "Paper",
  data() {
    return {
      // 试卷详情
      paper: {},
      questionList: [],
      //  学科列表
      subjectList: [],
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 试卷表格数据
      paperList: [],
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        paperName: null,
        subjectId: null,
        limitStartTime: null,
        limitEndTime: null,
      },
    };
  },
  created() {
    this.getSubjectList();
    this.getPaperList();
  },
  methods: {
    // 权限校验
    checkPermi,
    // 开始考试
    async handleDoExam(row) {
      let res = await doExam({ paperId: row.paperId });
      // console.log(res);s
      if (res && res.data) {
        console.log(res.data);
        this.$router.push({
          path: "/doExam",
          props: true,
          query: {
            paperId: row.paperId,
            paperAnswerId: res.data.paperAnswerId,
            doExamEndTime: res.data.doExamEndTime,
          },
        });
      }
    },
    /**修改状态 */
    async handleStatus(row) {
      console.log(row);
      try {
        await updatePaperStatus(row.paperId, row.status);
        this.$modal.msgSuccess("状态修改成功");
      } catch (error) {
        //   正常点击是不会走这里的，除非自己加参数
        this.getPaperList();
        console.log("error", error);
      }
    },

    /** 查询学科列表 */
    async getSubjectList() {
      try {
        // this.loading = true;
        let { data } = await listSubject(this.queryParams);
        this.subjectList = data.records;
        // this.total = data.total;
        // this.loading = false;
      } catch (error) {
        console.log(error);
        this.$modal.error("获取学科列表失败");
      }
    },
    /** 查询试卷列表 */
    async getPaperList() {
      try {
        this.loading = true;

        /*   console.log(new Date(this.queryParams.limitStartTime).valueOf()); */
        /**
         *调整为时间戳
         */
        this.queryParams.limitStartTime
          ? (this.queryParams.limitStartTime = new Date(
              this.queryParams.limitStartTime
            ).valueOf())
          : null;

        this.queryParams.limitEndTime
          ? (this.queryParams.limitEndTime = new Date(
              this.queryParams.limitEndTime
            ).valueOf())
          : null;

        let { data } = await listPaper(this.queryParams);
        this.paperList = data.records;
        this.total = data.total;
        this.loading = false;
      } catch (error) {
        this.loading = false;
        console.log(error);
        this.$modal.error("获取试卷列表失败");
      }
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getPaperList();
    },
    /** 重置搜索按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({
        path: "/paper/add",
      });
    },
    /** 查看试卷详情  */
    async handlePreview(row) {
      console.log("查看试卷详情");
      this.open = true;
      let { data } = await getPaper(row.paperId);
      this.paper = data.paper;
      // 后端在再试卷没有试题的清空下返回null
      this.questionList = data.paperAndQuestion || [];
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除试卷编号为"' + '"的数据项？')
        .then(function () {
          console.log(row.paperId);
          return delPaper(row.paperId);
        })
        .then(() => {
          this.getPaperList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>
<style lang="scss" scoped>
.paperInfo {
  div {
    font-weight: 400;

    margin: 10px 0;
    .el-tag {
      margin-right: 10px;
    }
  }
}
</style>
